package com.bbs.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.bbs.dao.AdminDao;
import com.bbs.dto.MemberLogin;
import com.bbs.dto.MemberRegister;
import com.bbs.dto.SearchBean;
import com.bbs.model.Member;
import com.bbs.model.Topic;
import com.bbs.util.Page;

@Component("admindao")
public class AdminDaoImpl extends HibernateDAO implements AdminDao {

	 private static final Log log = LogFactory.getLog(AdminDaoImpl.class);
	
	public boolean addMember(MemberRegister register) {
		Member member = new Member(register);

		return this.create(member);
	}

	public boolean loginMember(MemberLogin memberlogin) {
		String hql = "select m.mid from Member as m inner join m.rolesid as r where m.mname=? and m.mpassword=? and r.rolepermission>2";
		List list = this.getHibernateTemplate().find(hql,
				memberlogin.getLoginname(), memberlogin.getLoginpwd());
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

	public List<Member> loadMembers(SearchBean searchbean, Page page) {
		List<Member> list = null;

		if (searchbean == null) {
			String count = "select count(*) from Member as m";
			int rowCount = Integer.parseInt(this.getHibernateTemplate().find(
					count).get(0).toString());
			String hql = "from Member as m";

			if (page == null) {
				page = new Page(rowCount, 10, 1);
			} else {
				page.setRowCount(rowCount);
			}
			list = this.getListForPage(hql, page.getCurrentPage(), 10);
		} else {
			list = new ArrayList<Member>();
			Member member = (Member) this.loadByKey(Member.class, searchbean
					.getName(), searchbean.getValue());
			list.add(member);
		}

		return list;
	}

	public List<Topic> loadTopics(SearchBean searchbean, Page page) {
		List<Topic> list = null;

		if (searchbean == null) {
			String count = "select count(*) from Topic as t";
			int rowCount = Integer.parseInt(this.getHibernateTemplate().find(
					count).get(0).toString());
			String hql = "from Topic as t";

			if (page == null) {
				page = new Page(rowCount, 10, 1);
			} else {
				page.setRowCount(rowCount);
			}
			list = this.getListForPage(hql, page.getCurrentPage(), 10);
		} else {
			list = new ArrayList<Topic>();
			Topic topic = (Topic) this.loadByKey(Topic.class, searchbean
					.getName(), searchbean.getValue());
			list.add(topic);
		}

		return list;
	}

}
